package br.unifor.cct.mia.select;

import br.unifor.cct.mia.evolutionary.FeatureConstructionGenotype;
import br.unifor.cct.mia.ga.Ga;
import br.unifor.cct.mia.util.Methods;

public class FeatureConstructionTournament implements Select {

    private FeatureConstructionGenotype[] newPopulation;
    private int n=3;
    
    public Object execute(Object value) {
    	Object[] o = (Object[])value;
		Ga Ga = (Ga)o[0];
		
        newPopulation = new FeatureConstructionGenotype[Ga.configurations.getPopsize()+1];
        return tournament(Ga);
    }
    
    private FeatureConstructionGenotype[] tournament(Ga Ga){
    	int count = 1;
    	if ( Ga.population[Ga.configurations.getPopsize()] != null ) {//Ja adiciona o melhor
    		newPopulation[Ga.configurations.getPopsize()] = (FeatureConstructionGenotype)Ga.population[Ga.configurations.getPopsize()].clone();    		
    		newPopulation[0] = (FeatureConstructionGenotype)Ga.population[Ga.configurations.getPopsize()].clone();
    	}
    	
    	while ( count < newPopulation.length ) {
	    	int individuos[] = new int[n];
	    	for ( int i=0; i<n; i++ ) {
	    		int val = Methods.randIntValue(0,Ga.configurations.getPopsize()-1);
	    		while ( Methods.arrayContains(individuos,val) ) {
	    			val = Methods.randIntValue(0,Ga.configurations.getPopsize()-1);
	    		}
	    		individuos[i] = val;
	    	}
	    	
	    	FeatureConstructionGenotype select = (FeatureConstructionGenotype)Ga.population[individuos[0]];
	    	for ( int i=0; i<individuos.length; i++ ) {
	    		int index = individuos[i];
	    		FeatureConstructionGenotype ind = (FeatureConstructionGenotype)Ga.population[index];
	    		if ( ind.getFitness() > select.getFitness() ) {
	    			select = ind;
	    		}
	    	}
	    	
	    	newPopulation[count] = (FeatureConstructionGenotype)select.clone();
	    	count++;
    	}
        
        System.arraycopy(newPopulation, 0, Ga.population, 0, Ga.configurations.getPopsize());
        
        return (FeatureConstructionGenotype[])Ga.population;
    }	
	
}
